#!/bin/bash

# Check if the env_vars file path, Dockerfile path, and placeholder name are provided as arguments
if [ $# -ne 3 ]; then
    echo "Error: Please provide the path to the env_vars file, the path to the Dockerfile, and the placeholder name as arguments."
    exit 1
fi

# Get the path to the env_vars file
env_vars="$1"
# Get the path to the Dockerfile
dockerfile_path="$2"
# Get the placeholder name
placeholder="$3"

# Check if the env_vars file exists
if [ ! -f "$env_vars" ]; then
    echo "Error: The $env_vars file was not found!"
    exit 1
fi

# Check if the Dockerfile exists
if [ ! -f "$dockerfile_path" ]; then
    echo "Error: The $dockerfile_path file was not found!"
    exit 1
fi

# Initialize the environment variable string
combined_env_vars=""

# Read the key-value pairs from the env_vars file
while IFS='=' read -r key value; do
    # Skip comment lines starting with '#'
    if [[ $key == \#* ]]; then
        continue
    fi
    # Trim leading and trailing whitespace from the key and value
    key=$(echo "$key" | xargs)
    value=$(echo "$value" | xargs)
    # Skip empty lines
    if [ -z "$key" ]; then
        continue
    fi
    # Skip key-value pairs with empty values and print a log
    if [ -z "$value" ]; then
        echo "Warning: Skipping key '$key' as its value is empty."
        continue
    fi
    # Combine the key-value pair
    combined_env_vars+=" $key=\"$value\""
done < "$env_vars"

# Use the sed command to replace the placeholder with the combined environment variables
sed -i "s|$placeholder|ENV$combined_env_vars|g" "$dockerfile_path"

echo "The environment variable settings have replaced the placeholder in $dockerfile_path!"    
echo "new docker file content is:"
cat $dockerfile_path